import sys
sys.path.append('bgui/')

import starfield
import bgui
from bgui import *
import bge



class Visualizer():
	#Juggles bgui widgets if they are representing a game object
	
	def __init__(self):
		self.scene = bge.logic.getCurrentScene()
		self.camera = self.scene.objects["Camera"]
		self.displayed_stars = []
		self.displayed_planets = []
		self.displayed_ships = []
		
		#game object visualization
		self.starlabels = {}
		self.starframes = {}
		self.ships = {}
		
		self.selected_system = -1
		
		#This is the bgui frame that Visualizer uses
		self.display = starfield.UI.visualized
		
		self.display.on_click = self.on_click
		self.display.on_release = self.on_release
		self.display.on_active = self.on_active
		
		self.timer_size = 0
		self.timer_view = 0
		
		#selection
		self.select_rect = 0
		self.select_start = 0
		self.select_end = 0
	
	def on_click(self, widget):
		
		mouse = bge.logic.mouse
		mouse_pos = list(mouse.position)[:]
		self.select_start = mouse_pos[:]
		self.select_end = mouse_pos[:]
				
				
		if self.select_rect == 0:
			self.select_rect = Frame( self.display, "select", size=[.001,.001], pos=[mouse_pos[0], 1-mouse_pos[1]],
													 sub_theme="Select", options= BGUI_DEFAULT )
		
	def on_active(self, widget):
		if self.select_rect != 0:
			mouse = bge.logic.mouse
			mouse_pos = list(mouse.position)[:]
			self.select_end = mouse_pos[:]
			
			width = abs(self.select_start[0] - self.select_end[0] )
			height = abs(self.select_start[1] - self.select_end[1] )
			
			if self.select_start[0] < self.select_end[0]:
				if self.select_start[1] > self.select_end[1]:
					offset = [self.select_start[0], 1-self.select_start[1]]
				else:
					offset = [self.select_start[0], 1-self.select_end[1] ]
			else:
				if self.select_start[1] > self.select_end[1]:
					offset = [self.select_end[0], 1-self.select_start[1] ]
				else:
					offset = [self.select_end[0], 1-self.select_end[1] ]
			self.select_rect._update_position(size = [width, height], pos=offset)
		
	def on_release(self, widget):
		mouse = bge.logic.mouse
		mouse_pos = list(mouse.position)
		if self.select_rect != 0:
			self.display._remove_widget(self.select_rect)
			self.select_rect = 0

	def spawnObject(self, objectName, worldPosition = [0.0, 0.0, 0.0]):
		newObject = self.scene.addObject(objectName, "Placer")
		newObject.worldPosition = worldPosition
		
		return newObject
		
	def update(self, galaxy):
		for system in galaxy:
			if galaxy[system].object == 0:
				newStar = self.spawnObject("Star", galaxy[system].location)
				newStar.localScale = [5000 + 10000*starfield.SCALE*2]*3
				galaxy[system].object = newStar
				print("MAKING STAR: ", galaxy[system].name)
				
				
				
				
	def Pump(self, galaxy):

		starfield.camera_orientation = self.camera.orientation
		self.drawStarNames(galaxy)
	

	
	def drawStarNames(self, galaxy):
		self.timer_view += 1
		
		if self.timer_view > 3:
			self.timer_view = 0
			# fist let's get the nearby stars
			in_box = []
			within = []
			#print(self.camera.position)
			starfield.star_oct.root.get_within(self.camera.position, 200*starfield.STAR_MAX_DISTANCE * starfield.SCALE, in_box)
			for entry in in_box:
				if self.camera.pointInsideFrustum(entry.location):
					within.append(entry)
			
			
			#print("WITHIN CAMERA: ", len(within))	
			
			
				
			selsz = .01
				
			#remove any star widgets
			cleanup = []
			for entry in self.starframes:
				star = galaxy[entry]
				if star not in within:
					widget = self.starframes[entry]
					cleanup.append(entry)
					self.display._remove_widget(widget)
			for entry in cleanup:
				self.starframes.pop(entry)
					
			for star in within:
				if star.object != 0:
					
					
					
					
					if star.id not in self.starframes:
						npos = self.camera.getScreenPosition( star.object )
						self.starframes[star.id] = Frame( self.display, str(star.id), size=[.1,.1], pos=list(npos),
														 sub_theme="Dark", aspect=1, options= BGUI_DEFAULT )
														
						current = self.starframes[star.id]
						
						current.test= Frame( current, str(star.id)+"Test", size=[20,20], pos=list(npos),
														 sub_theme="Select",aspect=1, options= BGUI_THEMED | BGUI_CENTERED )
						
						current.test.border_color = [0.0,0.0,0.0,0.0]
						current.on_click = self.system_select
						
						current.namelabel = Label( current.test, str(star.id),  text="", 
														pt_size=12, pos=[0,0], color=(.3,.3,.3,1), options= BGUI_NORMALIZED | BGUI_CENTERX )
														
						current.ships = Label( current.test, str(star.id)+"ship",  text="", 
																pt_size=12, pos=[0,-1.0], options= BGUI_NORMALIZED  | BGUI_CENTERX  )
						
		for entry in self.starframes:
			star = starfield.galaxy[ entry ]
			current = self.starframes[star.id]
			npos = self.camera.getScreenPosition( star.object )
			rpos = [npos[0], 1-npos[1] - .004 ]
			
			
			dist = self.camera.getDistanceTo(star.location)
			s = .005 * ((starfield.STAR_MAX_DISTANCE * starfield.SCALE*2)/dist)
			ss = int(s*1000)
			if s < .008:
				s = .008
			if ss < 10:
				ss = 10
			spos = [npos[0]-(s/2), 1-npos[1]-(s/2)]

			current._update_position([s,s],list(spos))
			current.test._update_position(size=[ss,ss], pos=[.5,.5])
			
			#update name
			if star.name not in ["?", None]:
				if current.namelabel.text != star.name:
					current.namelabel.text = star.name
					

				
				
	def system_select(self, widget):
		name = widget.name[:]
		print("hi")
		if self.selected_system >= 0:
			if self.selected_system in self.starframes:
				self.starframes[ self.selected_system ].test.border_color=[0,0,0,0]	
		print("fi")	
		self.selected_system = int(name)
		print("fo")	
		star = starfield.galaxy[ self.selected_system ]
		print("fum")
		starfield.UI.current.info.select(star)
		print("I smell a leg drum")
		self.starframes[int(name)].test.border_color=[0,1,.6,1]
		

				